package com.moss.cloud.log.service.impl;

import com.moss.cloud.common.core.constant.Constant;
import com.moss.cloud.common.core.model.Result;
import com.moss.cloud.common.core.model.vo.CustomPage;
import com.moss.cloud.common.core.utils.BooleanHandel;
import com.moss.cloud.common.core.utils.MongoPageUtil;
import com.moss.cloud.common.core.utils.UserContextHolder;
import com.moss.cloud.log.model.param.LoginLogParam;
import com.moss.cloud.log.model.po.LoginLog;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import com.moss.cloud.log.service.ILoginLogService;
import reactor.core.publisher.Mono;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

@Service
public class LoginLogServiceImpl implements ILoginLogService {
    private MongoTemplate mongoTemplate;

    public LoginLogServiceImpl(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    /**
     * 保存登录日志
     *
     * @param loginLog
     * @return
     */
    @Override
    public Mono<Result> saveLoginLog(LoginLog loginLog) {
        loginLog.setId(UUID.randomUUID().toString());
        mongoTemplate.insert(loginLog);
        return Mono.just(Result.success());
    }

    /**
     * 分页查询登录日志
     *
     * @param loginLogParam
     * @return
     */
    @Override
    public CustomPage<LoginLog> logPage(LoginLogParam loginLogParam) {
        Query query = new Query();
        //创建排序规则
        Sort sort = Sort.by(Sort.Direction.DESC, "loginTime");
        query.with(sort);
        Criteria criteria = new Criteria();
        BooleanHandel.isTrue(StringUtils.isNotBlank(loginLogParam.getLoginStatus())).trueHandle(() ->
                criteria.and("loginStatus").is(loginLogParam.getLoginStatus()));
        BooleanHandel.isTrue(StringUtils.isNotBlank(loginLogParam.getUserName())).trueHandle(() ->
                criteria.and("userName").regex(Pattern.compile("^.*" + loginLogParam.getUserName() + ".*$", Pattern.CASE_INSENSITIVE)));
        Long tenantId = UserContextHolder.getTenantId();
        BooleanHandel.isTrue(!tenantId.equals(Constant.SUPER_TENANT)).trueHandle(() ->
                criteria.and("tenantId").is(tenantId));
        query.addCriteria(criteria);
        Long total = mongoTemplate.count(query, LoginLog.class);
        query.with(PageRequest.of(loginLogParam.getCurrent().intValue() - 1, loginLogParam.getSize().intValue()));
        List<LoginLog> loginLogs = mongoTemplate.find(query, LoginLog.class);
        return MongoPageUtil.customPage(loginLogs, loginLogParam.getCurrent(), loginLogParam.getSize(), total);
    }
}
